var express = require('express');
var router = express.Router();

// 导入db，操作数据库
const { getAll, getById, exec } = require('../db');

/**
 * 查找发布人id
 * GET /notice?username
 */
//  router.get('/', async (req, res) => {
//   const { username } = req.query;
//   let sql = `SELECT user_id FROM gg_user WHERE user_name='${username}'`;
//   const data = await getById(sql);
//   res.send({
//     code: 0,
//     message: '获取成功',
//     result: data,
//   });
// });

/**
 * 获取最新的公告
 * GET /notice
 */

router.get('/', async (req, res) => {
  let sql = `SELECT * FROM gg_notice ORDER BY notice_time DESC LIMIT 0,1`;
  const data = await getAll(sql);
  // 编写响应内容
  res.send({
    code: 0,
    message: '获取公告成功',
    result: data,
  });
});

/**
 * 新增
 * POST /notice
 */

router.post('/', async (req, res) => {
  const { user_id, notice_content, affected_area } = req.body;
  let sql = `insert into gg_notice (user_id,notice_content,affected_area) values (${user_id},'${notice_content}','${affected_area}')`;
  const data = await exec(sql);
  // 编写响应内容
  res.send({
    code: 0,
    message: '获取公告成功',
    result: {
      notice_id: data.insertId,
      user_id,
      notice_content,
      affected_area,
    },
  });
});

module.exports = router;
